module nehe.Lesson;

import derelict.opengl.gl;
import derelict.opengl.glu;
import derelict.sdl.sdl;

import tango.io.Stdout;

import nehe.Window;

public abstract class Lesson
{
	protected Window window; ///< The window for this lesson
	protected uint[SDLK_LAST] keys; ///< Stores keys that are pressed

	private bool running;
	
	public this()
	{
		window = new Window();
	}
	
	protected void resize(int x, int y)
	{
		Stdout("Resizing Window to ")(x)("x")(y).newline;

		if(y <= 0)
		{
			y = 1;
		}

		glViewport(0, 0, x, y);

		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		gluPerspective(45.0f, cast(GLfloat) x / cast(GLfloat) y, 1.0f, 100.0f);

		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
	}

	protected void processEvents()
	{
		SDL_Event event;
		// get all events
		while(SDL_PollEvent(&event))		
		{
			switch(event.type)
			{
				// Quit event
				case SDL_QUIT:
					// Return false because we are quitting.
					running = false;
					break;

				case SDL_KEYDOWN:
					SDLKey sym = event.key.keysym.sym;
					// Quit if escape was pressed
					if(sym == SDLK_ESCAPE)					
					{
						running = false;
						break;
					}

					keys[sym] = 1;
					break;

				case SDL_KEYUP:
					keys[event.key.keysym.sym] = 0;
					break;

				case SDL_VIDEORESIZE:
					// the window has been resized so we need to set up our viewport and projection according to 
					// the new size
					resize(event.resize.w, event.resize.h);
					break;
				default:
					break;
			}
		}
	}

	public abstract void init();

	protected abstract void draw();

	public void run()
	{
		running = true;
		while(running)
		{
			processEvents();
			draw();
			SDL_GL_SwapBuffers();
		}
	}
}
